package org.example.interceptor;

import cn.hutool.core.util.StrUtil;
import com.alibaba.druid.sql.SQLUtils;
import com.alibaba.druid.sql.ast.SQLExpr;
import com.alibaba.druid.sql.ast.SQLObject;
import com.alibaba.druid.sql.ast.expr.SQLIdentifierExpr;
import com.alibaba.druid.sql.ast.statement.SQLSelectItem;
import com.alibaba.druid.sql.dialect.mysql.ast.statement.MySqlSelectQueryBlock;

import java.util.ArrayList;
import java.util.List;

public class SqlUtil {
    private SqlUtil(){}
    public static String toJavaProperty(String columnName) {
        if (StrUtil.isBlank(columnName)) {
            throw new RuntimeException(columnName + " 不能为空");
        }
        StringBuilder sb = new StringBuilder();
        char[] chs = columnName.toCharArray();
        for (int i = 0; i < chs.length; i++) {
            if (chs[i] == '_') {
                i++;
                sb.append((char) (chs[i] - 'a' + 'A'));
            } else {
                sb.append(chs[i]);
            }
        }
        return sb.toString();
    }
    public static MySqlSelectQueryBlock findParent(SQLExpr x) {
        SQLObject parent = x.getParent();
        while (!(parent instanceof MySqlSelectQueryBlock)) {
            parent = parent.getParent();
        }
        return (MySqlSelectQueryBlock) parent;
    }
    public static MySqlSelectQueryBlock findParent(SQLObject x) {
        SQLObject parent = x.getParent();
        while (!(parent instanceof MySqlSelectQueryBlock)) {
            parent = parent.getParent();
        }
        return (MySqlSelectQueryBlock) parent;
    }
    public static List<SQLExpr> diff(List<SQLSelectItem> selectList, List<SQLExpr> items) {
        List<SQLExpr> res = new ArrayList<>();
        for (SQLExpr item : items) {
            String name = "";
            if (item instanceof SQLIdentifierExpr) {
                name = ((SQLIdentifierExpr) item).getName();
            } else {
                throw new RuntimeException("有其他的类型");
            }
            for (SQLSelectItem sqlSelectItem : selectList) {
                if (sqlSelectItem.getAlias() != null && sqlSelectItem.getAlias().equalsIgnoreCase(name)) {
                    break;
                }
                if (SQLUtils.toSQLString(sqlSelectItem.getExpr()).equalsIgnoreCase(name)) {
                    break;
                }
            }
            res.add(item);
        }
        return res;
    }
}
